package com.wuage.infrastructure.config;

import com.wuage.infrastructure.handler.JwtTokenFilter;
import com.wuage.infrastructure.security.JwtAccessDeniedHandler;
import com.wuage.infrastructure.security.JwtAuthenticationEntryPoint;
import com.wuage.infrastructure.security.JwtAuthorizationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import javax.annotation.Resource;

/**
 * @author Shynin
 * @version 1.0
 * @date 2020-09-03 00:15
 */
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    @Qualifier("jwtUserDetailsServiceImpl")
    private UserDetailsService userDetailsService;


    @Resource
    private JwtTokenFilter jwtTokenFilter;

    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Bean(name="authenticationManager")
    public AuthenticationManager getAuthenticationManager() throws Exception {
        return authenticationManager();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable()
                .authorizeRequests()
                // 需要登录了的用户才能访问
                .antMatchers("/auth/**", "/authentication/**", "/order/**","/role/**","/dictionary/**",
                        "/consult/**", "/financial/**", "/ssl/**", "/product/uac/**", "/statistics/**")
                .authenticated()
                // 管理员相关操作都需要管理员角色
                .antMatchers("/admin/**")
                .hasAuthority("ADMIN")
//                .hasRole("admin")
                .antMatchers("/superAdmin/**")
                .hasAuthority("SUPER_ADMIN")
                // 注册用户
                .antMatchers(HttpMethod.POST, "/account")
                .permitAll()
                // 获取验证码等绕过登录的url
                .antMatchers("/account/authCode", "/oauth/authentication",
                        "/file/**", "/article/**", "/account/email/authentication/**", "/product/**"
                        )
                .permitAll()
                // swagger相关
                .antMatchers("/doc.html","/swagger-resources","/v2/api-docs","/oauth/handler")
                .permitAll()
                .and()
                .addFilter(new JwtAuthorizationFilter(authenticationManager()))
                .addFilterBefore(jwtTokenFilter, JwtAuthorizationFilter.class)
                // 不需要session
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .exceptionHandling()
                .authenticationEntryPoint(new JwtAuthenticationEntryPoint())
                .and()
                .exceptionHandling()
                .accessDeniedHandler(new JwtAccessDeniedHandler());
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues());
        return source;
    }
}
